
/**
 * @ProjectName: 
 * @Copyright: 2014 lisheng  All Right Reserved.
 * @address: toughheart@163.com
 * @date: 2015年10月16日 下午9:40:58
 * @Description: 本内容未经本人允许禁止使用、转发.
 */
 
package com.ls.fw.web.file.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import javax.servlet.ServletContext;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.MultipartFile;

import com.ls.fw.commons.spring.SpringContextHolder;
import com.ls.fw.web.file.bean.FileErrorInfo;
import com.ls.fw.web.file.bean.UploadFileInfo;
import com.ls.fw.web.file.constant.Global;
import com.ls.fw.web.file.controller.BaseFileController.UploadResultHandler;
import com.ls.fw.web.file.service.FileService;


/**
 * 
 * @author lisheng
 * @date 2015年10月16日 下午9:40:58
 * @version V1.0 
 */
public class DefaultFileServiceImpl implements InitializingBean,
ServletContextAware , FileService{
	protected List<UploadResultHandler> resultHandlers = new ArrayList<UploadResultHandler>();
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	@Override
	public void success(String name, File destfile, UploadFileInfo fileInfo)
			throws Exception {
		for (UploadResultHandler handler : resultHandlers) {
			handler.success(name, destfile, fileInfo);
		}
	}
	
	@Override
	public void fail(String name, MultipartFile file, FileErrorInfo info,
			Exception e) throws Exception {
		for (UploadResultHandler handler : resultHandlers) {
			handler.fail(name, file, info, e);
		}
	}

	public List<UploadResultHandler> getResultHandlers() {
		return this.resultHandlers;
	}

	public void setResultHandlers(List<UploadResultHandler> resultHandlers) {
		this.resultHandlers = resultHandlers;
	}

	@Override
	public void setServletContext(ServletContext servletContext) {
		LinkedHashMap<String, String> map = Global.configInfo;
		if(map !=null){
			String handlers = map.get(Global.uploadResultHandler);
			if(StringUtils.isNotBlank(handlers)){
				String[] handlerss = handlers.split(",");
				for (String target : handlerss) {
				    UploadResultHandler  object = null;
					if(SpringContextHolder.containsBean(target)) {
				        object = SpringContextHolder.getBean(target);
				    }else {
				        try {
							object = (UploadResultHandler) SpringContextHolder.getBean(Class.forName(target));
						} catch (ClassNotFoundException e) {
							e.printStackTrace();
						}
				    }
				    if(object == null) {
				    	logger.warn(target+"对象不存在！");
				    }else{
				    	logger.info("加载"+target+"成功！");
				    	this.resultHandlers.add(object);
				    }
				}
			}
		}
		
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		// TODO Auto-generated method stub
		
	}

}
